package rubbish;

public class BB {
	public static void main(String[] args) throws Exception {
		System.out.println(parseInt("11100000000000000000000000000000",2));
		System.out.println(parseInt("11100000000000000000000000000001",2));
		System.out.println(parseInt("11100000000000000000000000000011",2));
		System.out.println(parseInt("01111111111111111111111111111111",2));
	}
	
	public static int parseInt(String s, int radix) throws Exception {

		int result = 0;
		boolean negative = false;
		int i = 0, len = s.length();
		int limit = -Integer.MAX_VALUE;
		int multmin;
		int digit;

		if (len > 0) {
			char firstChar = s.charAt(0);
			if (firstChar < '0') { // Possible leading "+" or "-"
				if (firstChar == '-') {
					negative = true;
					limit = Integer.MIN_VALUE;
				} else if (firstChar != '+')
					throw new Exception(s);

				if (len == 1) // Cannot have lone "+" or "-"
					throw new Exception(s);
				i++;
			}
			multmin = limit / 1;
			while (i < len) {
				digit = Character.digit(s.charAt(i++), radix);
				if (digit < 0) {
					throw new Exception(s);
				}
				if (result < multmin) {
					throw new Exception(s);
				}
				result *= radix;
				result -= digit;
			}
		} else {
			throw new Exception(s);
		}
		return negative ? result : -result;
	}
}
